//
//  WAOrderListController.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/13.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "WAOrderListController.h"
#import "WAOderTableHeadView.h"
#import "WAOderListCell.h"
#import "WATransactionDetailController.h"
#import "WAGoodsListViewModel.h"
#import "WAGoodListModel.h"
#import "WATransactionTotalDataModel.h"

@interface WAOrderListController ()<UITextFieldDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) WAOderTableHeadView *tableHeadView;
@property (nonatomic, strong) WAGoodsListViewModel *goodsListViewModel;
@property (assign, nonatomic) NSInteger pageNum;
@property (strong, nonatomic) NSMutableArray *dataSouces;
@property (strong, nonatomic) WATransactionTotalDataModel *totalDataModel;
@property (strong, nonatomic) NSArray *tenDataList;
@property (strong, nonatomic) NSString *phone;

@property (assign, nonatomic) NSInteger type;//0:买  1：卖
@end

@implementation WAOrderListController

- (instancetype)initWtihType:(NSInteger)type
{
    self = [super init];
    if (self) {
        self.type = type;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.dataSouces.count == 0) {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"WAOderListCell" bundle:nil] forCellReuseIdentifier:@"WAOderListCell"];
    
    self.tableHeadView = [[WAOderTableHeadView alloc] initWithFrame:CGRectMake(0, 0, WNScreenWidth, 460)];
    self.tableView.tableHeaderView = self.tableHeadView;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableHeadView.textFiled.delegate = self;
    
    @weakify(self)
    self.tableView.mj_header = [MJRefreshLoadHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.pageNum = 1;
        [self requestData];
        [self requestTotalData];
        [self requestTenData];
    }];
    self.tableView.mj_footer = [MJRefreshMoreFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.pageNum ++;
        [self requestData];
    }];
    self.tableView.tableFooterView = [UIView new];
    
    if (self.type == 0) {
        self.tableHeadView.buyTitleLb.text = @"买单";
    }else{
        self.tableHeadView.buyTitleLb.text = @"卖单";
    }
}

- (void)requestTenData{
    [self updateView];
    [WNBusinessRequest getTenDayTransactionDataWithType:self.type Succ:^(id  _Nonnull responseObject) {
        self.tenDataList = [WATransactionTenDataModel mj_objectArrayWithKeyValuesArray:responseObject];
        [self updateView];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        
    }];
}

- (void)requestTotalData{
    [WNBusinessRequest getTransactionTotalDataWithType:self.type Succ:^(id  _Nonnull responseObject) {
        self.totalDataModel = [WATransactionTotalDataModel mj_objectWithKeyValues:responseObject];
        if (self.type == 0) {
            self.loginManager.buy_maxValue = self.totalDataModel.highData;
            self.loginManager.buy_minValue = self.totalDataModel.lowData;
        }else{
            self.loginManager.sell_minValue = self.totalDataModel.lowData;
            self.loginManager.sell_maxValue = self.totalDataModel.highData;
        }
        [self updateView];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        
    }];
}

- (void)updateView{
    [self.tableHeadView configWithTenModel:self.tenDataList totalModel:self.totalDataModel];
}

- (void)requestData{
    [WNBusinessRequest  getTransactionListWithPageNum:self.pageNum
                                      transactiontype:self.type
                                               status:0
                                               phone:self.phone
                                                 Succ:^(id  _Nonnull responseObject) {
        NSDictionary *dict = (NSDictionary *)responseObject;
        NSInteger total = [dict[@"total"] integerValue];
        NSArray *memberList = [WAGoodListModel mj_objectArrayWithKeyValuesArray:dict[@"data"]];
        if (self.pageNum == 1) {
            self.dataSouces = [NSMutableArray new];
        }
        for (WAGoodListModel * model in memberList) {
            [self.dataSouces addObject:model];
        }
        if(total <= self.dataSouces.count){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView.mj_header endRefreshing];
        if (self.dataSouces.count == 0) {
            self.noDataStr = @"无数据";
            [WNTool show:@"无数据"];
        }else{
            [self.tableView reloadData];
        }
        [self.tableView reloadData];
        [self.tableView reloadEmptyDataSet];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        self.noDataStr = mes;
        [self.tableView reloadEmptyDataSet];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [WNTool show:mes];
    }];
}

#pragma mark - UITableView Delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WAOderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WAOderListCell"];
    cell.index = indexPath.row;
    NSString *btnTitle = self.type == 0 ? @"出售":@"购买";
    [cell.sellButton setTitle:btnTitle forState:0];
    [cell setBuyClickBlock:^(NSInteger index, id  _Nonnull objc) {
        WAGoodListModel *mo = (WAGoodListModel *)objc;
        if (mo.userid == self.userID_Int) {
            [WNTool show:[NSString stringWithFormat:@"不能%@自己的",btnTitle]];
            return;
        }
        if (!self.loginManager.isAuthentication) {
            [WNTool show:@"请先完善个人资料"];
            return;
        }
        //VIP0 不能发布买单和购买
        if (!self.loginManager.canPublish && self.type == 1) {
            [WNTool show:@"VIP0不能买单"];
            return;
        }
        [self sellBtnActionWithObj:mo];
    }];
    
    [cell setModel:self.dataSouces[indexPath.row]];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSouces.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.phone = textField.text;
    [self.tableView.mj_header beginRefreshing];
    return YES;
}
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if (textField.tag == 0) {
//        return YES;
//    }else{
//        if (textField.text.length > 18 && ![string isEqualToString:@""]) {
//            return NO;
//        }
//        return YES;
//    }
//}

- (void)sellBtnActionWithObj:(WAGoodListModel *)model{
    NSString *string;
    if (self.type == 0) {
        string = [NSString stringWithFormat:@"是否确定出售%zd个雨露，单价RM%.1f，要扣除一定比例的手续费",model.number,model.price];
    }else{
        string = [NSString stringWithFormat:@"是否确定购买%zd个雨露，单价RM%.1f",model.number,model.price];
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sellResultBtnActionWithObj:model];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)sellResultBtnActionWithObj:(WAGoodListModel *)model{
    
    [WNTool showLoading];
    [WNBusinessRequest updateTransactioninfoWithType:1 ID:model.ID status:1 image:nil Succ:^(id  _Nonnull responseObject) {
        if(self.type == 1){
            [WNTool show:@"购买成功！"];
        }else{
            [WNTool show:@"出售成功！"];
        }
        [self.tableView.mj_header beginRefreshing];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        [WNTool show:mes];
    }];
}

#pragma mark - DZNEmptyDataSetSource
//- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view{
//    [self.tableView.mj_header beginRefreshing];
//}
//
//- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView{
//    return [WNTool requestErrorWithSting:self.noDataStr];
//}
//
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
//    return 160;
//}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyBoardframe = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat spaceH = 40;
        // 强迫症，不能忍警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    UITextField *tf = [self.view.window performSelector:@selector(firstResponder)];
#pragma clang diagnostic pop
    CGRect rect1 = [self.view.window  convertRect:tf.frame fromView:tf.superview];
    CGFloat margin = keyBoardframe.size.height + spaceH - (WNScreenHeight - CGRectGetMaxY(rect1));
    if (margin <= 0) {
        return;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.transform = CGAffineTransformMakeTranslation(0, - margin);
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.transform = CGAffineTransformIdentity;
    }];
}

- (void)reload{
    [self.tableView.mj_header beginRefreshing];
}
@end
